import Dialog from '../external/youzan_dist/dialog/dialog';
var request_api = require('../../utils/require_api.js');
var a = new Set();
const app = getApp();
var t = require("../../utils/DownloadHelper.js");
let timeId = null;
Page({
  data: {
    riderCommentList: [],
    detailValue: '', //选择的公司名
    list: [
      { name: '设屏', id: 1 },
      {name: '推广',id: 2}
    ],
    CustomBar: app.globalData.CustomBar,
    current: 2, //进入小程序时，tab默认第一项
    buttonTop: 400,
    buttonLeft: 10,
    image_url: [], //传到wxml的图片地址
    url_image: [], //在这里的图片url地址
    openSettingBtnHidden: false, //是否需要重新授权的按钮隐藏与否
    showdapei: 2, //是否显示搭配，2是搭配样式界面，0和1是图片样式
    video_url: '', //视频播放地址
    indexonshow: 2, //判断是点击哪个tab
    maskshow: false, //遮罩层是否显示
    check_mark: false, //是否点击遮罩层上的对勾按钮
    showdownbtn: false, //是否显示下载按钮
    downurl: [], //选中需要下载的url
    paras: [], //post参数
    page: 1, //页数
    text: '', //查询关键字
    query_type: '图片',
    showKeywords: false, //是否显示关键字
    content: [], //推广的内容显示
    download_number: [],
    brandString: '',
    flag: true,
    floorstatus: false,
    tuiguangkey: '', //推广KEY  下载次数需要用到,
    tuiguangindex: 0,
    is_downloaded: [],
    is_all_downloads: [],
  },
  pair_paras(styleno, value, page, brand) { //传递后台参数
    this.data.paras = 
    [{"name": "ctype","value": styleno},
      {"name": "value","value": value},
      {"name": "page","value": page},
      {"name": "brand", "value": ''},
    ];
  },
  checkboxChange(e) { //选择品牌改变 
    this.data.brandString = ''; //OUTRIDE,SOTUOIA,BAT,Anmo
    this.pullrefresh(); //点击品牌触发
  },
  //下拉刷新
  onPullDownRefresh(e) {
    this.pullrefresh();
  },
  pullrefresh() {
    this.data.page = 1;
    if (this.data.indexonshow == 2) {
      var that = this;
      that.data.url_image = [];
      this.data.content = [];
      this.data.download_number = [];
      this.data.is_downloaded = [];
      this.data.is_all_downloads = [];
      this.pair_paras('3', '', this.data.page, this.data.brandString);
      this.get_tuiguang();
    }
  },
  //获取推广
  get_tuiguang() {
    var that = this;
    request_api.requesttype({
        "cmd": "weixin|get_img_video_match3",
        "paras": this.data.paras,
      }, 4, //这里4是类型4的意思 根据后台的类型设置
      function(res) {
        console.log(res.data.result,"this is res.data.result");
        wx.stopPullDownRefresh();
        for (let i = 0; i < res.data.result.length; i++) {
          that.data.content.push(res.data.result[i].content)
          that.data.download_number.push(res.data.result[i].downloads);
          that.data.is_downloaded.push(res.data.result[i].is_downloaded);
          that.data.is_all_downloads.push(res.data.result[i].is_all_downloads);
          if (res.data.result[i].sub1 != undefined) {
            for (let j = 0; j < res.data.result[i].sub1.length; j++) {
              if (res.data.result[i].sub1[j].ctype == 2) {
                res.data.result[i].sub1[j].poster = res.data.result[i].sub1[j].url + wx.getStorageSync('video_poster_AVI')
              }
              if (res.data.result[i].sub1[j].ctype==1){
                res.data.result[i].sub1[j].url = res.data.result[i].sub1[j].url + wx.getStorageSync('img_S1')
              }
            }
            that.data.url_image.push(res.data.result[i].sub1)
          }
        }
        that.setData({
          image_url: that.data.url_image, //推广图片
          content: that.data.content, //内容
          downloads: that.data.download_number, //下载数量
          is_downloaded: that.data.is_downloaded, //是否下载
          is_all_downloads: that.data.is_all_downloads, //是否必须下载
        })
      },
    )
  },
  onLoad: function(option) { 
    var that = this;
      that.setData({
        ismanager: wx.getStorageSync('ismanager')
      })
    if (option.tuiguang==1){
      this.data.showdapei = 1;
      this.setData({
        current:1,
        showdapei:1
      })
    } else{
      this.data.brandString = '';
      this.data.showdapei = 2;
      this.data.page = 1;
      this.pair_paras('3', '', this.data.page, this.data.brandString);
      that.data.url_image = [];
      this.data.content = [];
      this.data.download_number = [];
      this.data.is_downloaded = [];
      this.data.is_all_downloads = [];
      this.get_tuiguang(); 
    }
  },
  //点击tab切换事件
  onChange(event) { // 每次切换类型的时候都需要把页数置为1
    var that = this;
    this.data.url_image = [];
    this.data.indexonshow = event.target.dataset.current; //点击tab的下标
    this.data.page = 1;
    if (this.data.indexonshow == 2) { //设置搭配界面显示，设置不同数组
      this.data.showdapei = 2;
      this.pair_paras('3', '', this.data.page, this.data.brandString);
      that.data.url_image = [];
      this.data.content = [];
      this.data.download_number = [];
      this.data.is_downloaded = [];
      this.data.is_all_downloads = [];
      this.pair_paras('3', '', this.data.page, this.data.brandString);
      this.get_tuiguang();
    }
    this.setData({
      maskshow: false,
      image_url: this.data.url_image,
      showKeywords: false,
      showdapei: this.data.showdapei, //查看选择的是哪个按钮
      showdownbtn: false, //切换的时候隐藏下载按钮
      current: event.target.dataset.current,
    })
  },

  //是否显示下载按钮，根据有没有需要下载的图片
  isdownbtnshow(url) {
    if (url.length != 0) {
      this.data.showdownbtn = true;
    } else {
      this.data.showdownbtn = false
    }
  },

  onReachBottom: function(e) { //加载更多
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    setTimeout(() => { //加载600毫秒时间后查询数据
      ++that.data.page; //页数增加
      if (this.data.indexonshow == 2) {
        this.pair_paras('3', this.data.text, this.data.page, this.data.brandString);
        request_api.requesttype({
            "cmd": "weixin|get_img_video_match3",
            "paras": this.data.paras,
          }, 4, //这里4是类型4的意思 根据后台的类型设置
          function(res) {
            for (let i = 0; i < res.data.result.length; i++) {
              that.data.content.push(res.data.result[i].content)
              that.data.download_number.push(res.data.result[i].downloads);
              that.data.is_downloaded.push(res.data.result[i].is_downloaded);
              that.data.is_all_downloads.push(res.data.result[i].is_all_downloads);
              if (res.data.result[i].sub1 != undefined) {
                for (let j = 0; j < res.data.result[i].sub1.length; j++) {
                  if (res.data.result[i].sub1[j].ctype == 2) {
                    res.data.result[i].sub1[j].poster = res.data.result[i].sub1[j].url + wx.getStorageSync('video_poster_AVI')
                  }
                  res.data.result[i].sub1[j].url = res.data.result[i].sub1[j].url + wx.getStorageSync('img_S1')
                }
                that.data.url_image.push(res.data.result[i].sub1)
              }
            }
            that.setData({
              image_url: that.data.url_image, //推广图片
              content: that.data.content, //内容
              downloads: that.data.download_number, //下载数量
              is_downloaded: that.data.is_downloaded, //是否下载
              is_all_downloads: that.data.is_all_downloads, //是否必须下载
            })
          }
        )
      }
      wx.hideLoading();
    }, 800)
  },

  //页面滚动
  onPageScroll: function(res) {
    var that = this;
    setTimeout(function() {
      that.setData({
        buttonTop: 400 + res.scrollTop,
        buttonLeft: 10
      })
    }, 300);
    if (res.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }

  },
  goTop: function(e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //下载图片，显示遮罩层
  downloadbtn() {
    if (this.data.maskshow) {
      if (this.data.indexonshow == 0) {
        for (let i = 0; i < this.data.url_image.length; i++) {
          for (let j = 0; j < this.data.url_image[i].sub1.length; j++) {
            this.data.url_image[i].sub1[j].selected = false;
          }
        }
      } else if (this.data.indexonshow == 1) {
        for (let i = 0; i < this.data.url_image.length; i++) {
          this.data.url_image[i].selected = false;
        }
      }
      this.data.downurl = [];
    }
    this.setData({
      maskshow: !this.data.maskshow,
      image_url: this.data.url_image,
      showdownbtn: false,
    })
  },

  //设置下载次数
  set_download_times(tuiguangkey, index, download_statue) {
    let that = this;
    request_api.request({
        "cmd": "weixin|download_times",
        "paras": [{
            name: "tuiguang_key",
            value: tuiguangkey
          },
          {
            name: "openid",
            value: wx.getStorageSync("openid")
          }, //现在正式库的还没改脚本
          {
            name: 'download_statue',
            value: download_statue
          }
        ]
      }, //需要传的 data
      function(res) {
        console.log(res,"this is res,show resres resres");
        if (download_statue) {
          that.data.is_downloaded[index] = 1;
        }
        that.data.download_number[index] = res.data.result[0].downloads;
        that.setData({
          downloads: that.data.download_number,
          is_downloaded: that.data.is_downloaded //重新赋值是否已下载
        })
      },
      function() {
        console.log("错误");
      },
    )
  },
  //点击搭配的下载
  downloaddapei(e) {
    var that = this;
    this.data.downurl = e.detail.picture_download; //获取到的需要下载的url， 用于下载图片
    this.data.tuiguangkey = e.detail.tuiguangkey; //从推广页获取到的推广key用于下载次数
    this.data.tuiguangindex = e.detail.tuiguangindex; //从推广页获取到的需要下载推广的下标用于下载次数
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              if (e.detail.content != '') {
                wx.setClipboardData({ //复制文字内容
                  data: e.detail.content,
                  success: function(res) {
                    that.downloda(e.detail.type); //下载图片
                  }
                })
              } else {
                that.downloda(e.detail.type);
              }
            },
            fail() {
              if (e.detail.content != '') {
                wx.setClipboardData({ //复制文字内容
                  data: e.detail.content,
                  success: function(res) {
                    that.downloda(e.detail.type); //下载图片
                  }
                })
              } else {
                that.downloda(e.detail.type);
              }
            }
          })
        } else {
          if (e.detail.content != '') {
            wx.setClipboardData({ //复制文字内容
              data: e.detail.content,
              success: function(res) {
                that.downloda(e.detail.type); //下载图片
              }
            })
          } else {
            that.downloda(e.detail.type);
          }
        }
      }
    })
  },
  //点击下载区域下载内容
  downloda(e) { //下载的时候需要用到类型判断下载的是图片还是视频文件，用type来区分，
    var that = this;
    var type = '';
    var downloadsource = ''; //判断下载的来源  推广还是非推广  推广的话就需要弄个下载次数
    if (typeof(e) == 'string') {
      downloadsource = 'tuiguang';
      type = e;
    }
    wx.getSetting({ //首先判断是否授权，没有的话就弹出授权按钮，授权成功后才能下载
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          //没有授权获取相册
          wx.showToast({
            title: '请先授权！',
            duration: 2000, //显示时长
            mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
          });
          that.setData({
            openSettingBtnHidden: true, //授权不成功就调用去授权的按钮
            showdownbtn: true,
          })
          return;
        } else {
          var downer = new t.DownloadHelper(type); //创建新的对象，用于下载
          downer.download(that.data.downurl).then(function() { //调用下载对象的方法，传递需要下载的地址   下面是下载成功执行的内容
            wx.showToast({
              title: '下载成功！',
              duration: 3000, //显示时长
              mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
            });
            if (downloadsource != '') {
              that.set_download_times(that.data.tuiguangkey, that.data.tuiguangindex, 1); //设置下载次数，， 传入的是推广KEY和下标
            }
            that.setData({
              showdownbtn: false, //隐藏下载按钮
              maskshow: false, //去掉遮罩层
              image_url: that.data.url_image //把对勾去掉的数组重新赋值
            })
          }).catch(function(a) {
            wx.showToast({
              title: '下载失败！',
              duration: 3000, //显示时长
              mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
            });
            if (downloadsource != '') {
              that.set_download_times(that.data.tuiguangkey, that.data.tuiguangindex, 0); //设置下载次数  传入的是推广KEY和下标
            }
            wx.hideLoading();
            if (a.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || a.errMsg === 'saveVideoToPhotosAlbum:fail auth denied' || a.errMsg === 'saveImageToPhotosAlbum:fail auth deny' || a.errMsg === 'saveVideoToPhotosAlbum:fail auth deny') {
              wx.showToast({
                title: '请先授权',
                duration: 2000, //显示时长
                mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
              })
              wx.openSetting({
                success(settingdata) {
                  if (!settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
              that.setData({
                openSettingBtnHidden: true //授权不成功就调用去授权的按钮
              })
            }
          });
        }
      }
    })
  },
  //分享功能
  onShareAppMessage: function() {
    let users = wx.getStorageSync('user');
    return {
      title: '分享',
      path: "pages/index/index",
      success: function(res) {
        console.log("转发成功")
      }
    }
  },
  //跳转到user页面
  goUser() {
    wx.redirectTo({
      url: '../page/home/home',
    })
  }
})